/*
@file: transform.cpp
@author: ZZH
@date: 2022-05-05
@info: 变换函数实现文件
*/
#include "libFun.h"
#include "fft.h"

EXPORT void __dft(pFunCallArg_t pArgs, float* output)
{
    int allCalNum = pArgs->allCalNum;
    float* arg0 = static_cast<float*>(pArgs->args[0]);

    pComplex_t pOut = new Complex_t[allCalNum];

    rdft(pOut, arg0, allCalNum);

    memcpy(output, pOut, allCalNum * sizeof(float));
    delete[] pOut;
}

EXPORT void __idft(pFunCallArg_t pArgs, float* output)
{
    int allCalNum = pArgs->allCalNum;
    float* arg0 = static_cast<float*>(pArgs->args[0]);

    pComplex_t pIn = new Complex_t[allCalNum];
    memset(pIn, 0, allCalNum * sizeof(Complex_t));
    memcpy(pIn, arg0, allCalNum * sizeof(float));

    irdft(output, pIn, allCalNum);

    delete[] pIn;

    for (size_t i = 0;i < allCalNum;i++)
        output[i] /= allCalNum / 2;
}

EXPORT void __fft(pFunCallArg_t pArgs, float* output)
{
    int allCalNum = pArgs->allCalNum;
    float* arg0 = static_cast<float*>(pArgs->args[0]);

    pComplex_t pOut = new Complex_t[allCalNum];

    rfft(pOut, arg0, allCalNum);

    memcpy(output, pOut, allCalNum * sizeof(float));
    delete[] pOut;
}

EXPORT void __ifft(pFunCallArg_t pArgs, float* output)
{
    int allCalNum = pArgs->allCalNum;
    float* arg0 = static_cast<float*>(pArgs->args[0]);

    pComplex_t pIn = new Complex_t[allCalNum];
    memset(pIn, 0, allCalNum * sizeof(Complex_t));
    memcpy(pIn, arg0, allCalNum * sizeof(float));

    irfft(output, pIn, allCalNum);

    for (size_t i = 0;i < allCalNum;i++)
    {
        output[i] /= allCalNum / 2;
    }

    delete[] pIn;
}

LibFunction_t funcs[] = {
    LIB_FUNCTION(__dft, 1, .name = "dft"),
    LIB_FUNCTION(__idft, 1, .name = "idft"),
    LIB_FUNCTION(__fft, 1, .name = "fft"),
    LIB_FUNCTION(__ifft, 1, .name = "ifft"),
    END_OF_LIB
};

register_function_lib(funcs);
